<?php

namespace app\http\middleware;

use rsa\Rsa;

class Encrypt
{
    protected $open = false;
    public function handle($request, \Closure $next)
    {
        $rsa = new Rsa();
        if ($request->isPost() && $this->open == true) {
            $data = $request->post('data');
            $MAX_DECRYPT_BLOCK = 172;
            $ct = "";
            $str = strlen($data);
            $offSet = 0;
            $endOffSet = $MAX_DECRYPT_BLOCK;
            while ($str - $offSet > 0) {
                if ($str - $offSet > $MAX_DECRYPT_BLOCK) {
                    $bufTmp = substr($data, $offSet, $endOffSet);
                    $ct .= $rsa->privDecrypt($bufTmp);
                } else {
                    $bufTmp = substr($data, $offSet, $str);
                    $ct .= $rsa->privDecrypt($bufTmp);
                }
                $offSet += $MAX_DECRYPT_BLOCK;
            }
            $request->data = json_decode($ct, true);
        }
        return $next($request);
    }
}
